package com.yun.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yun.reggie.common.R;
import com.yun.reggie.entity.Category;
import com.yun.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author xiao
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> add(@RequestBody Category category){
        //log.info(category.toString());
        //因为设置了全局异常处理器，所以不用担心唯一性约束问题
        categoryService.save(category);
        return R.success("分类添加成功！");
    }

    @GetMapping("/page")
    public R<Page<Category>> page(int page,int pageSize){
        //log.info("page:{},pageSize:{}",page,pageSize);
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //分页数据按照sort进行排序
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper();
        wrapper.orderByAsc(Category::getSort);
        categoryService.page(pageInfo,wrapper);
        return R.success(pageInfo);
    }

    @DeleteMapping
    public R<String> delete(Long ids){
        //log.info("删除的id：{}",ids);
        categoryService.delete(ids);
        return R.success("删除成功！");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
        //log.info(category.toString());
        categoryService.updateById(category);
        //因为设置了业务异常处理，所以不会违反唯一性约束
        return R.success("修改成功！");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper();
        wrapper.eq(category.getType() != null,Category::getType,category.getType());
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }

}
